package com.msh.automatic.android.api.configurer.interceptor;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.msh.automatic.android.api.util.DeviceActivationInfoUtil;
import com.msh.automatic.android.api.util.JwksUtil;
import com.msh.automatic.android.api.util.RetUtil;
import com.nimbusds.jwt.SignedJWT;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class DeviceActivationInterceptor implements HandlerInterceptor {

    @Resource
    JwksUtil jwksUtil;
    @Resource
    DeviceActivationInfoUtil deviceActivationInfoUtil;
    //调用目标方法之前执行的方法
    //如果返回ture表示拦截器验证成功，执行目标方法
    //如果返回false表示拦截器验证失败，不再继续执行后续业务
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //用户登录判断业务
        String token = request.getHeader("x-msh-token");
        if(StrUtil.isEmpty(token)){
            response.setStatus(200);
            response.setContentType("application/json; charset=UTF-8");
            response.setCharacterEncoding(CharsetUtil.UTF_8);
            IoUtil.write(response.getOutputStream(), CharsetUtil.CHARSET_UTF_8,false, JSON.toJSONString(RetUtil.error("SESSION_NOT_FIND","未登录")));
            return false;
        }
        SignedJWT jwt = jwksUtil.verify(token);
        if(jwt == null){
            response.setStatus(200);
            response.setContentType("application/json; charset=UTF-8");
            response.setCharacterEncoding(CharsetUtil.UTF_8);
            IoUtil.write(response.getOutputStream(), CharsetUtil.CHARSET_UTF_8,false, JSON.toJSONString(RetUtil.error("SESSION_NOT_FIND","未登录")));
            return false;
        }
        DeviceActivationInfoUtil.set(jwt);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        DeviceActivationInfoUtil.remove();
    }
}